const app = getApp()
import { getProjectIslandList } from '../../../../api/index'
import { formatTimeTwo } from '../../../../utils/util'

Page({
  data: {
    pageSize: 15,
    currentPage: 1,
    safeBottom: 0,
    isEmpty: false,
    list: [],
    keyword: '',
    refresher: false
  },
  async onRefresh () {
    await this.getList()
    this.setData({ refresher: false })
  },
  search ({ detail }) {
    this.setData({ keyword: detail })
    this.getList()
  },
  seeDetail ({ currentTarget: { dataset: { item } } }) {
    wx.$nav.navigateTo(`/pages/account/island/detail/index?id=${item.id}&roleids=${item.role_ids.join(',')}`)
  },
  async loadMore () {
    try {
      if (this.loading || this.alloaded) return
      this.loading = true
      let query = {
        page: this.data.currentPage,
        per_page: this.data.pageSize
      }
      if (this.data.keyword) query.material_keyword = this.data.keyword
      const { ResultSet } = await getProjectIslandList({ ...query })
      this.alloaded = !ResultSet.userData.data.length
      this.data.isEmpty = !ResultSet.userData.data.length
      this.setData({ isEmpty: this.data.isEmpty })
      if (ResultSet.userData.data.length) {
        this.data.currentPage = this.data.currentPage + 1
        this.data.list.push(...ResultSet.userData.data)
        this.setData({
          list: this.data.list,
          currentPage: this.data.currentPage
        })
      }
      this.loading = false
    } catch (err) {
      console.log(err)
      this.loading = false
      wx.showToast({ title: err.message || err.ResultSet.errors })
    }
  },
  async getList () {
    try {
      let query = {
        page: 1,
        per_page: this.data.pageSize
      }
      if (this.data.keyword) query.material_keyword = this.data.keyword
      const { ResultSet } = await getProjectIslandList({ ...query })
      let list = ResultSet.userData && ResultSet.userData.data && ResultSet.userData.data.length ? ResultSet.userData.data : []
      list.forEach(item => {
        item.created_at = formatTimeTwo(item.created_at * 1000, 'Y-M-D')
      })
      if (list.length) this.data.currentPage = 2
      this.data.isEmpty = list.length && list.length < this.data.pageSize
      this.setData({
        list: list,
        currentPage: this.data.currentPage,
        isEmpty: this.data.isEmpty
      })
    } catch (err) {
      console.log(err)
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  onLoad () {
    const { screenHeight, safeArea: { bottom } } = wx.$pro.getSystemInfoSync()
    this.setData({ safeBottom: screenHeight - bottom })
    this.getList()
  }
})